const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
const fs = require('fs');
const authRoutes = require('./routes/auth');
const noticeRoutes = require('./routes/notice');
const mlaRoutes = require('./routes/minLivingAllowance');
const complaintRoutes = require('./routes/complaints');
const activityRoutes = require('./routes/activities');
const uploadRoutes = require('./routes/upload');
const serviceItemsRoutes = require('./routes/serviceItems');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件配置
app.use(cors({
  origin: '*', // 生产环境请设置具体的域名
  credentials: true
}));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 静态文件服务 - 提供图片等静态资源
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.use('/public', express.static(path.join(__dirname, 'public')));

// 请求日志中间件已移除

// 路由配置
app.use('/api/auth', authRoutes);
app.use('/api/notice', noticeRoutes);
app.use('/api/min-living-allowance', mlaRoutes);
app.use('/api/complaints', complaintRoutes);
app.use('/api/activities', activityRoutes);
app.use('/api/upload', uploadRoutes);
app.use('/api/service-items', serviceItemsRoutes);

// 健康检查接口
app.get('/api/health', (req, res) => {
  res.json({
    success: true,
    message: '乡村政务系统后端服务运行正常',
    timestamp: new Date().toISOString()
  });
});

// 测试静态文件服务
app.get('/api/test-uploads', (req, res) => {
  const fs = require('fs');
  const path = require('path');
  const uploadsDir = path.join(__dirname, 'uploads');
  
  try {
    const files = fs.readdirSync(uploadsDir);
    res.json({
      success: true,
      message: 'uploads目录文件列表',
      data: {
        uploadsDir: uploadsDir,
        files: files,
        count: files.length
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '读取uploads目录失败',
      error: error.message
    });
  }
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在'
  });
});

// 错误处理中间件
app.use((error, req, res, next) => {
  console.error('服务器错误:', error);
  res.status(500).json({
    success: false,
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? error.message : undefined
  });
});

// 启动服务器
async function startServer() {
  try {
    // 设置开发模式
    process.env.NODE_ENV = 'development';
    
    // 启动HTTP服务器
    app.listen(PORT, () => {
      console.log(`服务器运行在端口 ${PORT}`);
      console.log(`环境模式: ${process.env.NODE_ENV}`);
      // 活动状态自动更新服务已在start-auto-update.js中启动
    });
  } catch (error) {
    console.error('启动服务器失败:', error);
    process.exit(1);
  }
}

startServer();

module.exports = app;
